// 考勤记录管理模块
const AttendanceManager = {
    // 当前页码
    currentPage: 1,
    
    // 每页记录数
    pageSize: 20,
    
    // 总记录数
    totalRecords: 0,
    
    // 当前筛选条件
    filters: {
        startDate: '',
        endDate: '',
        employeeId: '',
        deviceId: ''
    },
    
    // 初始化
    init() {
        this.initEventListeners();
        this.initFilters();
        this.loadAttendanceRecords();
    },
    
    // 初始化事件监听器
    initEventListeners() {
        // 同步数据按钮
        document.getElementById('sync-attendance-btn').addEventListener('click', () => {
            this.syncAttendanceData();
        });
        
        // 导出记录按钮
        document.getElementById('export-attendance-btn').addEventListener('click', () => {
            this.exportAttendanceRecords();
        });
        
        // 查询按钮
        document.getElementById('search-attendance-btn').addEventListener('click', () => {
            this.searchAttendanceRecords();
        });
        
        // 日期输入框变化
        document.getElementById('start-date').addEventListener('change', (e) => {
            this.filters.startDate = e.target.value;
        });
        
        document.getElementById('end-date').addEventListener('change', (e) => {
            this.filters.endDate = e.target.value;
        });
        
        // 员工筛选
        document.getElementById('employee-filter').addEventListener('change', (e) => {
            this.filters.employeeId = e.target.value;
        });
        
        // 设备筛选
        document.getElementById('device-filter').addEventListener('change', (e) => {
            this.filters.deviceId = e.target.value;
        });
    },
    
    // 初始化筛选器
    async initFilters() {
        // 设置默认日期范围（最近7天）
        const endDate = new Date();
        const startDate = new Date();
        startDate.setDate(startDate.getDate() - 7);
        
        document.getElementById('start-date').value = this.formatDateInput(startDate);
        document.getElementById('end-date').value = this.formatDateInput(endDate);
        
        this.filters.startDate = this.formatDateInput(startDate);
        this.filters.endDate = this.formatDateInput(endDate);
        
        // 加载员工和设备选项
        await this.loadFilterOptions();
    },
    
    // 加载筛选器选项
    async loadFilterOptions() {
        try {
            // 并行加载员工和设备列表
            const [employeesResponse, devicesResponse] = await Promise.all([
                AttendanceApp.api('/employee/list'),
                AttendanceApp.api('/device/list')
            ]);
            
            // 填充员工选项
            const employeeSelect = document.getElementById('employee-filter');
            employeeSelect.innerHTML = '<option value="">全部员工</option>';
            
            const employees = employeesResponse.data || [];
            employees.forEach(employee => {
                const option = document.createElement('option');
                option.value = employee.id;
                option.textContent = `${employee.name} (${employee.employeeId})`;
                employeeSelect.appendChild(option);
            });
            
            // 填充设备选项
            const deviceSelect = document.getElementById('device-filter');
            deviceSelect.innerHTML = '<option value="">全部设备</option>';
            
            const devices = devicesResponse.data || [];
            devices.forEach(device => {
                const option = document.createElement('option');
                option.value = device.id;
                option.textContent = device.name;
                deviceSelect.appendChild(option);
            });
            
        } catch (error) {
            console.error('加载筛选器选项失败:', error);
        }
    },
    
    // 格式化日期输入
    formatDateInput(date) {
        return date.toISOString().split('T')[0];
    },
    
    // 加载考勤记录
    async loadAttendanceRecords(page = 1) {
        try {
            AttendanceApp.showLoading();
            
            this.currentPage = page;
            
            const params = new URLSearchParams({
                page: this.currentPage,
                pageSize: this.pageSize,
                ...this.filters
            });
            
            const response = await AttendanceApp.api(`/attendance/records?${params}`, {
                method: 'POST',
                body: JSON.stringify(this.filters)
            });
            
            const data = response.data || {};
            this.totalRecords = data.total || 0;
            const records = data.records || [];
            
            this.renderAttendanceTable(records);
            this.renderPagination();
            
            AttendanceApp.hideLoading();
        } catch (error) {
            console.error('加载考勤记录失败:', error);
            AttendanceApp.hideLoading();
            AttendanceApp.showNotification('加载考勤记录失败', 'error');
        }
    },
    
    // 渲染考勤记录表格
    renderAttendanceTable(records) {
        const tbody = document.getElementById('attendance-tbody');
        tbody.innerHTML = '';
        
        if (records.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="8" style="text-align: center; padding: 40px; color: #666;">
                        <i class="fas fa-clock" style="font-size: 2rem; margin-bottom: 10px; opacity: 0.3;"></i>
                        <p>暂无考勤记录</p>
                    </td>
                </tr>
            `;
            return;
        }
        
        records.forEach(record => {
            const row = this.createAttendanceRow(record);
            tbody.appendChild(row);
        });
    },
    
    // 创建考勤记录行
    createAttendanceRow(record) {
        const row = document.createElement('tr');
        row.dataset.recordId = record.id;
        
        const syncStatusClass = this.getSyncStatusClass(record.syncStatus);
        const syncStatusText = this.getSyncStatusText(record.syncStatus);
        const punchTypeText = this.getPunchTypeText(record.punchType);
        const verifyModeText = this.getVerifyModeText(record.verifyMode);
        
        row.innerHTML = `
            <td>${record.employeeName || '未知员工'}</td>
            <td>${record.employeeId || '-'}</td>
            <td>${AttendanceApp.formatDate(record.punchTime)}</td>
            <td>${punchTypeText}</td>
            <td>${verifyModeText}</td>
            <td>${record.deviceName || '未知设备'}</td>
            <td>
                <span class="sync-status-badge ${syncStatusClass}">
                    <i class="fas fa-circle"></i>
                    ${syncStatusText}
                </span>
            </td>
            <td>
                <button class="btn btn-sm btn-secondary" onclick="AttendanceManager.viewRecordDetail('${record.id}')">
                    <i class="fas fa-eye"></i>
                </button>
                ${record.syncStatus === 'FAILED' ? `
                    <button class="btn btn-sm btn-warning" onclick="AttendanceManager.retrySyncRecord('${record.id}')">
                        <i class="fas fa-redo"></i>
                    </button>
                ` : ''}
                <button class="btn btn-sm btn-danger" onclick="AttendanceManager.deleteRecord('${record.id}')">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        `;
        
        return row;
    },
    
    // 获取同步状态样式类
    getSyncStatusClass(status) {
        const classes = {
            'SYNCED': 'synced',
            'PENDING': 'pending',
            'FAILED': 'failed'
        };
        return classes[status] || 'pending';
    },
    
    // 获取同步状态文本
    getSyncStatusText(status) {
        const texts = {
            'SYNCED': '已同步',
            'PENDING': '待同步',
            'FAILED': '同步失败'
        };
        return texts[status] || '未知';
    },
    
    // 获取打卡类型文本
    getPunchTypeText(type) {
        const texts = {
            'IN': '上班',
            'OUT': '下班',
            'BREAK_OUT': '外出',
            'BREAK_IN': '返回',
            'OVERTIME_IN': '加班开始',
            'OVERTIME_OUT': '加班结束'
        };
        return texts[type] || type || '未知';
    },
    
    // 获取验证方式文本
    getVerifyModeText(mode) {
        const texts = {
            'FINGERPRINT': '指纹',
            'FACE': '人脸',
            'CARD': '刷卡',
            'PASSWORD': '密码',
            'PALM': '掌纹'
        };
        return texts[mode] || mode || '未知';
    },
    
    // 渲染分页
    renderPagination() {
        const container = document.getElementById('attendance-pagination');
        container.innerHTML = '';
        
        const totalPages = Math.ceil(this.totalRecords / this.pageSize);
        
        if (totalPages <= 1) {
            return;
        }
        
        // 上一页按钮
        const prevBtn = document.createElement('button');
        prevBtn.textContent = '上一页';
        prevBtn.disabled = this.currentPage === 1;
        prevBtn.onclick = () => this.loadAttendanceRecords(this.currentPage - 1);
        container.appendChild(prevBtn);
        
        // 页码按钮
        const startPage = Math.max(1, this.currentPage - 2);
        const endPage = Math.min(totalPages, this.currentPage + 2);
        
        if (startPage > 1) {
            const firstBtn = document.createElement('button');
            firstBtn.textContent = '1';
            firstBtn.onclick = () => this.loadAttendanceRecords(1);
            container.appendChild(firstBtn);
            
            if (startPage > 2) {
                const ellipsis = document.createElement('span');
                ellipsis.textContent = '...';
                ellipsis.style.padding = '8px 12px';
                container.appendChild(ellipsis);
            }
        }
        
        for (let i = startPage; i <= endPage; i++) {
            const pageBtn = document.createElement('button');
            pageBtn.textContent = i;
            pageBtn.className = i === this.currentPage ? 'active' : '';
            pageBtn.onclick = () => this.loadAttendanceRecords(i);
            container.appendChild(pageBtn);
        }
        
        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                const ellipsis = document.createElement('span');
                ellipsis.textContent = '...';
                ellipsis.style.padding = '8px 12px';
                container.appendChild(ellipsis);
            }
            
            const lastBtn = document.createElement('button');
            lastBtn.textContent = totalPages;
            lastBtn.onclick = () => this.loadAttendanceRecords(totalPages);
            container.appendChild(lastBtn);
        }
        
        // 下一页按钮
        const nextBtn = document.createElement('button');
        nextBtn.textContent = '下一页';
        nextBtn.disabled = this.currentPage === totalPages;
        nextBtn.onclick = () => this.loadAttendanceRecords(this.currentPage + 1);
        container.appendChild(nextBtn);
        
        // 显示记录信息
        const info = document.createElement('div');
        info.style.marginTop = '10px';
        info.style.textAlign = 'center';
        info.style.color = '#666';
        info.textContent = `共 ${this.totalRecords} 条记录，第 ${this.currentPage}/${totalPages} 页`;
        container.appendChild(info);
    },
    
    // 搜索考勤记录
    searchAttendanceRecords() {
        this.currentPage = 1;
        this.loadAttendanceRecords();
    },
    
    // 同步考勤数据
    async syncAttendanceData() {
        try {
            const btn = document.getElementById('sync-attendance-btn');
            const originalText = btn.innerHTML;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 同步中...';
            btn.disabled = true;
            
            const response = await AttendanceApp.api('/attendance/sync', {
                method: 'POST'
            });
            
            if (response.success) {
                const data = response.data;
                AttendanceApp.showNotification(
                    `同步完成：成功 ${data.totalSynced} 条，失败 ${data.totalFailed} 条`, 
                    'success'
                );
                
                // 重新加载当前页面数据
                this.loadAttendanceRecords(this.currentPage);
            } else {
                throw new Error(response.message || '同步失败');
            }
        } catch (error) {
            console.error('同步考勤数据失败:', error);
            AttendanceApp.showNotification('同步考勤数据失败: ' + error.message, 'error');
        } finally {
            const btn = document.getElementById('sync-attendance-btn');
            btn.innerHTML = '<i class="fas fa-sync"></i> 同步数据';
            btn.disabled = false;
        }
    },
    
    // 导出考勤记录
    async exportAttendanceRecords() {
        try {
            const btn = document.getElementById('export-attendance-btn');
            const originalText = btn.innerHTML;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 导出中...';
            btn.disabled = true;
            
            const params = new URLSearchParams(this.filters);
            const response = await fetch(`${AttendanceApp.apiBase}/attendance/export?${params}`, {
                method: 'GET',
                headers: {
                    'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                }
            });
            
            if (response.ok) {
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `考勤记录_${this.filters.startDate}_${this.filters.endDate}.xlsx`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);
                
                AttendanceApp.showNotification('考勤记录导出成功', 'success');
            } else {
                throw new Error('导出失败');
            }
        } catch (error) {
            console.error('导出考勤记录失败:', error);
            AttendanceApp.showNotification('导出考勤记录失败: ' + error.message, 'error');
        } finally {
            const btn = document.getElementById('export-attendance-btn');
            btn.innerHTML = '<i class="fas fa-download"></i> 导出记录';
            btn.disabled = false;
        }
    },
    
    // 查看记录详情
    async viewRecordDetail(recordId) {
        try {
            const response = await AttendanceApp.api(`/attendance/record/${recordId}`);
            const record = response.data;
            
            if (!record) {
                AttendanceApp.showNotification('记录不存在', 'error');
                return;
            }
            
            const content = `
                <div style="line-height: 1.8;">
                    <div style="margin-bottom: 15px;">
                        <strong>员工信息：</strong><br>
                        姓名：${record.employeeName || '未知'}<br>
                        工号：${record.employeeId || '未知'}<br>
                        部门：${record.employeeDepartment || '未知'}
                    </div>
                    <div style="margin-bottom: 15px;">
                        <strong>打卡信息：</strong><br>
                        时间：${AttendanceApp.formatDate(record.punchTime)}<br>
                        类型：${this.getPunchTypeText(record.punchType)}<br>
                        验证方式：${this.getVerifyModeText(record.verifyMode)}
                    </div>
                    <div style="margin-bottom: 15px;">
                        <strong>设备信息：</strong><br>
                        设备名称：${record.deviceName || '未知'}<br>
                        设备位置：${record.deviceLocation || '未知'}
                    </div>
                    <div style="margin-bottom: 15px;">
                        <strong>同步信息：</strong><br>
                        同步状态：${this.getSyncStatusText(record.syncStatus)}<br>
                        同步时间：${record.syncTime ? AttendanceApp.formatDate(record.syncTime) : '未同步'}
                    </div>
                    ${record.remark ? `
                        <div style="margin-bottom: 15px;">
                            <strong>备注：</strong><br>
                            ${record.remark}
                        </div>
                    ` : ''}
                </div>
            `;
            
            AttendanceApp.showModal('考勤记录详情', content, [
                {
                    text: '关闭',
                    class: 'btn-secondary',
                    onclick: () => AttendanceApp.hideModal()
                }
            ]);
            
        } catch (error) {
            console.error('获取记录详情失败:', error);
            AttendanceApp.showNotification('获取记录详情失败', 'error');
        }
    },
    
    // 重试同步记录
    async retrySyncRecord(recordId) {
        try {
            const response = await AttendanceApp.api(`/attendance/retry-sync/${recordId}`, {
                method: 'POST'
            });
            
            if (response.success) {
                AttendanceApp.showNotification('重新同步成功', 'success');
                
                // 更新表格中的记录状态
                const row = document.querySelector(`[data-record-id="${recordId}"]`);
                if (row) {
                    const statusCell = row.querySelector('.sync-status-badge');
                    statusCell.className = 'sync-status-badge synced';
                    statusCell.innerHTML = '<i class="fas fa-circle"></i> 已同步';
                }
            } else {
                throw new Error(response.message || '重新同步失败');
            }
        } catch (error) {
            console.error('重新同步记录失败:', error);
            AttendanceApp.showNotification('重新同步失败: ' + error.message, 'error');
        }
    },
    
    // 删除记录
    async deleteRecord(recordId) {
        AttendanceApp.confirm('确定要删除这条考勤记录吗？此操作不可恢复。', async () => {
            try {
                const response = await AttendanceApp.api(`/attendance/delete/${recordId}`, {
                    method: 'POST'
                });
                
                if (response.success) {
                    AttendanceApp.showNotification('记录删除成功', 'success');
                    
                    // 重新加载当前页面数据
                    this.loadAttendanceRecords(this.currentPage);
                } else {
                    throw new Error(response.message || '删除失败');
                }
            } catch (error) {
                console.error('删除记录失败:', error);
                AttendanceApp.showNotification('删除记录失败: ' + error.message, 'error');
            }
        });
    }
};

